package studio.raptor.ddal.demo.jmeter.oracle;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import studio.raptor.ddal.core.connection.BackendConnection;
import studio.raptor.ddal.core.connection.BackendDataSourceManager;
import studio.raptor.ddal.core.executor.resultset.ResultData;

/**
 * @author Sam
 * @since 3.0.0
 */
public class JdbcSelectSampler extends AbstractJavaSamplerClient {

  private static final AtomicLong ID = new AtomicLong(System.currentTimeMillis());

  @Override
  public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
    SampleResult sampleResult = new SampleResult();
    sampleResult.sampleStart();
    BackendConnection conn = null;
    try  {
      conn = BackendDataSourceManager.getBackendConnection("group_1", false, false);
      ResultData statement = conn.executePreparedUpdate(JMeterConstants.INSERT, Arrays.asList((Object)ID.getAndIncrement()));

      if (null != statement && statement.getAffectedRows() == 1) {
        sampleResult.setSuccessful(true);
      } else {
        sampleResult.setSuccessful(false);
      }
      conn.commit();
    } catch (Exception e) {
      e.printStackTrace();
      sampleResult.setSuccessful(false);
    } finally {
      if(null != conn) {
        try {
          conn.close();
        } catch (Exception e) {
          conn.close();
        }
      }
    }
    sampleResult.sampleEnd();
    return sampleResult;
  }

}
